public without sharing class TaskAmountDivideController {

	public String msg {get;set;}
	public Boolean isErr {get;set;}//是否正确;
	public Boolean isSuccess {get;private set;}//是否成功
	public String mcId {get;set;}//拆分的测算ID ; 
	public String startDate {get;set;}//开始日期;

  public Boolean isSimpleCalc {get;private set;}//是否简易测算

	public String saveJson  {get;set;}//保存结果 
  public String paramJson {get; private set;}

  public String backId  {get;private set; }

  public Measure_Calculate__c mc { get; private set; }
  public class ControllerException extends Exception {}



    public TaskAmountDivideController() {
       	

    	mcId  = System.currentPageReference().getParameters().get('id');
    	startDate = '';
      backId = '';
      isSimpleCalc = false ;
    	setNil();
    }

    ///获取测算明细
    public void getDetails(){

        if(isSimpleCalc){///简易测算明细
          MeasureCalcFillSimpleController mcc = new MeasureCalcFillSimpleController();
          paramJson  = mcc.getDetails(mc.Id);

        }else{//标准测算明细
          MeasureCalcController mcc = new MeasureCalcController();
          paramJson  = mcc.getDetails(mc.Id);
        }


    }
    ///获取测算
    private void getMc(String mc_Id ){
       // 获取测算
        Schema.DescribeSobjectResult m = Measure_Calculate__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();
        
        String sql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        sql += fields;
      
///还有3个成本价格字段;
        sql +=',RecordType.DeveloperName , Opportunity__r.AccountId ,Opportunity__r.ExecutiveCompany__c,Opportunity__r.ExecutiveCompany__r.RecordType.DeveloperName '; 
         
        sql += ' from Measure_Calculate__c where Id = \'' + mc_Id + '\'';

        mc = Database.query(sql);

        isSimpleCalc = mc.RecordType.DeveloperName  == 'SimpleCalculation' ;

    }

  
    public void init(){

      
      try {

         if(mcId == null)setError('页面打开错误!');
         if(Id.valueOf(mcId).getSObjecttype() != Measure_Calculate__c.SObjectType)setError('页面打开错误!');
         User u = [select Profile.Name  from User where Id =: UserInfo.getUserId()];
         if(u.Profile.Name != '系统管理员' && !u.Profile.Name.contains('财务'))setError('没有操作权限!');
          getMc(mcId);
          
      }catch (Exception e) {
         ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));
 
      }
      
     
  

    }
  

    /*@RemoteAction
    public static List<Map<String,String>> findMC(String mcname ){

    	List<Map<String,String>> mcL  = new List<Map<String,String>>();

    	if(mcname == null || mcname.trim().length() == 0) return mcL;
    	mcname = '%'+mcname.trim()+'%'; 
    	//
    	for(Measure_Calculate__c mc :[select Id,Name from Measure_Calculate__c where Status__c ='审批成功' and  Name like: mcname limit 10 ]){
    		Map<String,String> mMap = new Map<String,String>();
    		mMap.put('Id', mc.Id);
    		mMap.put('Name', mc.Name );
    		mcL.add(mMap);
    	}
    	return mcL;

    }*/
   
    ///保存拆分的数据
    public void save(){

    	msg = '';
    	List<TaskRelatedMeasure__c>  trmL = [select Id,MeasureCalc__r.Name,MeasureCalc__r.CoopYear__c   from TaskRelatedMeasure__c where  MeasureCalc__c =:mcId];
    	if(trmL.size() > 0){
    		msg = trmL[0].MeasureCalc__r.Name +' 拆分已经关联!请不要重复关联!';
    		return;
    	}

    	if(startDate == ''|| mcId == ''){
    		msg = '测算和开始日期不能为空!';
    		return ; 
    	}
      Integer coopYear = Integer.valueOf(mc.CoopYear__c.substring(0, mc.CoopYear__c.length() - 1));

    	Date d = Date.valueOf(startDate);
   
       
		List<Object>  tabList = (List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
    

      Map<String,Map<Integer,Decimal>> proCostMap = new Map<String,Map<Integer,Decimal>>();
      Map<String,Map<Integer,Decimal>> proGroupCostMap = new Map<String,Map<Integer,Decimal>>();
      Map<String,Map<Integer,Decimal>> proSalesMap = new Map<String,Map<Integer,Decimal>>();

		for (Object o  :tabList ) {
			
			Map<String,Object> tam = (Map<String,Object>)o ; 
      String key = String.valueOf(tam.get('cate1'))+'_'+String.valueOf(tam.get('brand'))+'_'+String.valueOf(tam.get('cate2'));
      Map<String,Object> am = (Map<String,Object> ) tam.get('am');
      Map<String,Object> sm = (Map<String,Object> ) tam.get('sm');
      Map<String,Object> gm = (Map<String,Object> ) tam.get('gm');

      Map<Integer,Decimal>  gmMap = new Map<Integer,Decimal>();
      Map<Integer,Decimal> smMap = new Map<Integer,Decimal>();
      Map<Integer,Decimal> amMap = new Map<Integer,Decimal>();
      for (String k :am.keySet() ) {

            amMap.put(Integer.valueOf(k), Decimal.valueOf(String.valueOf(am.get(k)) ));
            smMap.put(Integer.valueOf(k),Decimal.valueOf(String.valueOf(sm.get(k))));
            gmMap.put(Integer.valueOf(k),Decimal.valueOf(String.valueOf(gm.get(k))));
      }
      proSalesMap.put(key,amMap);
      proCostMap.put(key,smMap);
      proGroupCostMap.put(key,gmMap);

		}

        ///匹配公司
    Map<String,String > comMap = ImportObject.getPicklistValues('CooperationStandard__c', 'Company__c', false);

      Date sd = Date.valueOf(startDate);
      Date ed = Date.newInstance(sd.year(), sd.month(), 1).addMonths(coopYear * 12).addDays(-1);

      Id accId = mc.Opportunity__r.ExecutiveCompany__r.RecordType.DeveloperName =='Maccura' ? mc.Opportunity__r.AccountId : mc.Opportunity__r.ExecutiveCompany__c ;//开票客户
      Id teraccId= mc.Opportunity__r.AccountId;//终端客户
      CooperationStandard__c cs  = null ;
            System.debug('TaskAmountDivideController==>'+accId);
            System.debug('TaskAmountDivideController==>'+ teraccId);

        try{
             cs =  [select Id ,Company__c ,EndingDate__c,StartingDate__c  from CooperationStandard__c  where NewData__c = true 
            and Account__c =:accId and TerminalCustomer__c =:teraccId  limit 1 ]; 


            if(cs.EndingDate__c.daysBetween(ed ) > 0)cs.EndingDate__c = ed ;
          
            if(sd.daysBetween(cs.StartingDate__c) > 0 )cs.StartingDate__c = sd;
        }catch(Exception e){
            System.debug('TaskAmountDivideController==>'+ e.getMessage() + e.getStackTraceString());
            cs =  new CooperationStandard__c();
            cs.Account__c = accId;
            cs.TerminalCustomer__c = teraccId;
            cs.NewData__c = true; //标记是新生成的任务量主表

            cs.Company__c = comMap.get(mc.Company__c)  ;
            System.debug('TaskAmountDivideController==>'+ mc.Company__c);
            System.debug('TaskAmountDivideController==>'+ comMap);
            if(cs.company__c == null){
              msg = '测算公司没有维护!';
              return ;
            }
            cs.StartingDate__c = sd;
            cs.EndingDate__c = ed ;
           // cs.company__c = comMap.get(tti.OwnerCompany__c);

        }

    SavePoint sp1 = Database.setSavepoint();
    try {
        upsert cs Id; 
    }catch (Exception e) {
        isSuccess = false;
        Database.rollback(sp1);
        msg = '保存失败!'+e.getMessage() + e.getStackTraceString();
        return;
    }
    


    List<TaskAmount__c> tList = new List<TaskAmount__c>();
    List<MearsureCalcUtil.TaskBean> tabL = MearsureCalcUtil.dispatchTask( proSalesMap,  proCostMap,  proGroupCostMap, d,  coopYear);
    for (MearsureCalcUtil.TaskBean ta:  tabL) {
      tList.add(MearsureCalcUtil.genFromBean(ta,  cs.Id,  mcId));
    }
		TaskRelatedMeasure__c trm = new TaskRelatedMeasure__c();
		trm.StartDate__c = d;
		trm.MeasureCalc__c = mcId;
		trm.Standers__c = cs.Id;
       	SavePoint sp = Database.setSavepoint();
       	try {
       	    
       	    if(tList.size() > 0) {
       	    	 insert trm;
       	    	 upsert  tList;
       	    	 msg = '保存成功!' ;
       	    	 isSuccess = true;
               backId = cs.Id ; 
       	    }
       	}catch (Exception e) {
       		isSuccess = false;
       	    Database.rollback(sp);
            Database.rollback(sp1);
       	    msg = '保存失败!'+e.getMessage() + e.getStackTraceString();

       	}
       	

    }

    //置空变量
    public void setNil(){
    	isErr = false;
    	msg = '';
    	saveJson = '[]';
      paramJson = '{}';
    
    }
    //设置错误
    private void setError(String message){
    	isErr = true;
      throw new ControllerException(message);

    }


}